package com.macro.mall.portal.config;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hrequest = (HttpServletRequest)servletRequest;
        String accept = hrequest.getHeader("accept");
        if (StringUtils.equals("application/json", accept)) {
//            //注入我们重写的request请求
//            servletRequest = new BodyReaderHttpServletRequestWrapper(hrequest);

//            try{
//                try(BufferedReader reader = hrequest.getReader()){
//                    StringBuilder sb = new StringBuilder();
//                    String s;
//                    while((s = reader.readLine()) != null) {
//                        sb.append(s.trim());
//                    }
//                    if (sb != null) {
//                        try {
//                            JSONObject jsonObject = JSONObject.parseObject(sb.toString());
//                            for (String key:jsonObject.keySet()) {
//                                servletRequest.setAttribute(key, jsonObject.get(key));
//                                hrequest.getSession().setAttribute(key, jsonObject.get(key));
//                            }
//                        } catch (Exception e) {
//                        }
//                    }
//                }
//            } catch (IOException e) {
//            }
//            HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
//            wrapper.sendRedirect(hrequest.getContextPath() + hrequest.getServletPath());
        }
        filterChain.doFilter(servletRequest, servletResponse);

//        if(hrequest.getRequestURI().indexOf("/index") != -1 ||
//                hrequest.getRequestURI().indexOf("/asd") != -1 ||
//                hrequest.getRequestURI().indexOf("/online") != -1 ||
//                hrequest.getRequestURI().indexOf("/login") != -1
//        filterChain.doFilter(servletRequest, servletResponse);
//        ) {
//        }else {
//            wrapper.sendRedirect("/login");
//        }
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
